package com.cskaoyan.config;

import com.cskaoyan.converter.String2DateConverter;
import com.cskaoyan.interceptor.CustomHandlerInterceptor;
import com.cskaoyan.interceptor.CustomHandlerInterceptor2;
import com.cskaoyan.interceptor.CustomHandlerInterceptor3;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.format.FormatterRegistry;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import java.util.Locale;

@ComponentScan("com.cskaoyan.controller")
@EnableWebMvc //mvc:annotation-driven
public class WebConfiguration implements WebMvcConfigurer {//mvc标签的方法

    @Bean
    public LocaleResolver localeResolver() {
        CookieLocaleResolver localeResolver = new CookieLocaleResolver();
        localeResolver.setCookieName("language");
        localeResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return localeResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //                                      mapping                          location
        registry.addResourceHandler("/pic1/**").addResourceLocations("file:d:/spring/");
        registry.addResourceHandler("/pic2/**").addResourceLocations("classpath:/");
    }

    //HandlerInterceptor是谁、作用范围是什么、顺序
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomHandlerInterceptor());//默认的作用范围
        registry.addInterceptor(new CustomHandlerInterceptor2()).addPathPatterns("/hello/**");//作用范围
        registry.addInterceptor(new CustomHandlerInterceptor3()).addPathPatterns("/hello/**");//作用范围

    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new String2DateConverter());
    }

    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        localValidatorFactoryBean.setProviderClass(HibernateValidator.class);
        return localValidatorFactoryBean;
    }
}
